package pl.edu.agh.gronoMining.owlToGraphConverter.parser.utils.implementation;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import pl.edu.agh.gronoMining.owlToGraphConverter.parser.utils.IDataManager;
import pl.edu.agh.gronoMining.owlToGraphConverter.parser.utils.NodeData;

public class DataManager implements IDataManager{

	private Map<Integer, NodeData> integerToDataMap;
	private Map<NodeData, Integer> dataToIntegerMap;
	private int nextInt;
	
	public DataManager() {
		this.integerToDataMap = new HashMap<Integer, NodeData>();
		this.dataToIntegerMap = new HashMap<NodeData, Integer>();
		nextInt = 1;
	}
	
	public int getInt(NodeData data) {
		Integer i = this.dataToIntegerMap.get(data);
		if (i == null) {
			i = nextInt++;
			this.integerToDataMap.put(i, data);
			this.dataToIntegerMap.put(data, i);
		}
		return i;
	}
	
	public NodeData getData(int id) {
		return this.integerToDataMap.get(id);
	}
	
	public void serialize(String filename) throws IOException {
		File f = new File(filename);
		f.createNewFile();
		OutputStream stream = new FileOutputStream(f);
		ObjectOutput serialStream = new ObjectOutputStream(stream);
		try {
			serialStream.writeObject(this.integerToDataMap);
			serialStream.writeObject(this.dataToIntegerMap);
		} finally {
			serialStream.close();
		}
		this.integerToDataMap = new HashMap<Integer, NodeData>();
		this.dataToIntegerMap = new HashMap<NodeData, Integer>();
	}
	
	public void deserialize(String filename) throws IOException {
		File f = new File(filename);
		InputStream stream = new FileInputStream(f);
		ObjectInput serialStream = new ObjectInputStream(stream);
		try {
			this.integerToDataMap = (Map<Integer, NodeData>) serialStream.readObject();
			this.dataToIntegerMap = (Map<NodeData, Integer>) serialStream.readObject();
		} catch (ClassNotFoundException e) {
			throw new IOException(e.getMessage());
		} finally {
			serialStream.close();
		}
		f.delete();
	}	
	
}
